package com.ktg.mes.rec.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.mes.pro.domain.ProRouteProcess;
import com.ktg.mes.pro.service.IProRouteProcessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.rec.domain.RecProcessesExt;
import com.ktg.mes.rec.service.IRecProcessesExtService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 工序项Controller
 *
 * @author byteco
 * @date 2022-11-04
 */
@RestController
@RequestMapping("/rec/recProcessesExt")
public class RecProcessesExtController extends BaseController
{
    @Autowired
    private IRecProcessesExtService recProcessesExtService;

    @Autowired
    private IProRouteProcessService proRouteProcessService;

    /**
     * 查询工序项列表
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:list')")
    @GetMapping("/list")
    public Result<IPage<RecProcessesExt>> list(RecProcessesExt recProcessesExt,
                                               @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                               HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询工序项列表",req,null);
        try {
            Page<RecProcessesExt> page = new Page<RecProcessesExt>(pageNo, pageSize);
            IPage<RecProcessesExt> pageList = recProcessesExtService.queryPageList(recProcessesExt,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 更新后台排序查询工序项列表
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:list')")
    @GetMapping("/listOrder")
    public Result<IPage<RecProcessesExt>> listOrder(RecProcessesExt recProcessesExt,
                                               @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                               HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("更新后台排序查询工序项列表",req,recProcessesExt);
        try {
            Page<RecProcessesExt> page = new Page<RecProcessesExt>(pageNo, pageSize);
            QueryWrapper<RecProcessesExt> lqw = new  QueryWrapper();
            lqw.orderByAsc("order_backstage");
            IPage<RecProcessesExt> pageList = recProcessesExtService.page(page,lqw);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 根据工序id查询工序项 不分页
     */
    @GetMapping("/extList")
    public Result<RecProcessesExt> getExtList(RecProcessesExt recProcessesExt,HttpServletRequest req){
        APIResult apiLog = new APIResult("查询工序项列表-不分页",req,null);
        try{
            List<RecProcessesExt> list = recProcessesExtService.list(
                    new LambdaQueryWrapper<RecProcessesExt>().eq(RecProcessesExt::getProcessId, recProcessesExt.getProcessId()));
            return apiLog.ok(list);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出工序项列表
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:export')")
    @Log(title = "工序项", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RecProcessesExt recProcessesExt,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出工序项列表",req,recProcessesExt);
        try {
            List<RecProcessesExt> list = recProcessesExtService.queryList(recProcessesExt);
            ExcelUtil<RecProcessesExt> util = new ExcelUtil<RecProcessesExt>(RecProcessesExt.class);
            util.exportExcel(response, list, "工序项数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取工序项详细信息
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:query')")
    @GetMapping(value = "/{id}")
    public Result<RecProcessesExt> getInfo(@PathVariable("id") Long id,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取工序项详细信息",req,null);
        try {
            RecProcessesExt info = recProcessesExtService.getInfo(id);
            return apiLog.ok(recProcessesExtService.getInfo(id));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增工序项
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:add')")
    @Log(title = "工序项", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<String> add(@RequestBody RecProcessesExt recProcessesExt,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增工序项",req,recProcessesExt);
        try {
            String error = recProcessesExt.jSONErrorString();
            if (error != null){
                return apiLog.fail(error);
            }
            recProcessesExtService.insert(recProcessesExt);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 新增工序项
     */
    @Log(title = "工序项", businessType = BusinessType.INSERT)
    @GetMapping("/pdaFind")
    public Result<String> findPDA(@RequestParam("recordId") Long recordId ,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增工序项",req,String.valueOf(recordId));
        try {
            ProRouteProcess proRouteProcess = proRouteProcessService.getById(recordId);

            QueryWrapper<RecProcessesExt> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("process_id",proRouteProcess.getProcessId());
            queryWrapper.isNotNull("name_pda");
            queryWrapper.orderByAsc("order_pda");
            List<RecProcessesExt> mapList = recProcessesExtService.list(queryWrapper);

            List<RecProcessesExt> recProcessesExtList = new ArrayList<>();
            //把工艺流程的配置参数返回
            if (!StringUtils.isEmpty(proRouteProcess.getParamJson())){
                JSONObject jsonObject = JSONObject.parseObject(proRouteProcess.getParamJson());
                for (int i = 0;i < mapList.size();i++){
                    if (StringUtils.isEmpty(mapList.get(i).getNamePda())){
                        continue;
                    }
                    String a =  jsonObject.getString(mapList.get(i).getNameBackstage());
                    if ("N".equals(a)){ //后台设置不需要的
                        continue;
                    }
                    if (a != null){
                       mapList.get(i).setNameBackstage(a);
                    }else {
                       mapList.get(i).setNameBackstage(null);
                    }
                    recProcessesExtList.add(mapList.get(i));
                }
            }
            return apiLog.ok(recProcessesExtList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 修改工序项
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:edit')")
    @Log(title = "工序项", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<String> edit(@RequestBody RecProcessesExt recProcessesExt,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改工序项",req,recProcessesExt);
        try {
            String error = recProcessesExt.jSONErrorString();
            if (error != null){
                return apiLog.fail(error);
            }
            recProcessesExtService.update(recProcessesExt);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除工序项
     */
    @PreAuthorize("@ss.hasPermi('rec:recProcessesExt:remove')")
    @Log(title = "工序项", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<String> remove(@PathVariable Long[] ids,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除工序项",req,null);
        try {
            recProcessesExtService.delete(ids);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }
}
